# -*- coding: utf-8 -*-

# @File    : reder_response.py
# @Date    : 2021-05-17
# @Author  : allyzeng



from rest_framework.renderers import JSONRenderer

class customrenderer(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        code =20000
        if renderer_context:
            if isinstance(data, dict):
                msg = data.pop('msg', 'success')
                code = data.pop('code', 20000)
            else:
                msg = 'success'
                code = 20000

            # 重新构建返回的JSON字典
            if data == None or data == '':
                data = ''
            else:
                for key in data:
                    # 判断是否有自定义的异常的字段
                    if key == 'message':
                        code = 0
                        msg = data[key]
                        data = ''
            ret = {
                'code': code,
                'msg': msg,
                'data': data,
            }
            # 返回JSON数据
            if(code == 20000):
                return super().render(ret)
            return super().render(ret, accepted_media_type, renderer_context)
        else:
            return super().render(data, accepted_media_type, renderer_context)
